package com.triones.yjj.controller.api.wx;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.common.config.YjjExternalAuthConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.exception.ServiceException;
import com.triones.framework.common.util.weixin.*;
import com.triones.yjj.entity.WithdrawalRecordDO;
import com.triones.yjj.mapper.WithdrawalRecordMapper;
import com.triones.yjj.service.WxPayService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 微信商户、退款、提现等业务
 *
 * @Author: triones
 */
@SaIgnore
@Slf4j
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/api/wx/mch")
public class WxMchController extends BaseController {

    private YjjExternalAuthConfig yjjExternalAuthConfig;

    private final WxPayService wxPayService;

    private final WithdrawalRecordMapper withdrawalRecordMapper;

//    @RequestMapping(value="createResSign",method={RequestMethod.POST,RequestMethod.GET})
//    @ResponseBody
//    public Map<String, Object> createResSign(HttpServletRequest req, HttpServletResponse res){
//        res.setCharacterEncoding("UTF-8");
//        try {
//            GetPublicKey getPublicKey = new GetPublicKey();
//            System.out.println("返回的公钥信息" + getPublicKey.getPublicKey());
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return null;
//    }

    /**
     * 微信提现到银行卡
     * @param req
     * @param res
     * @return
     */
    @RequestMapping(value="wxWithdrawal",method={RequestMethod.POST,RequestMethod.GET})
    @ResponseBody
    public R<Void> wxWithdrawal(HttpServletRequest req,
                                            HttpServletResponse res){
        res.setCharacterEncoding("UTF-8");
        String codeNum = req.getParameter("codeNum");
        String userName = req.getParameter("userName");
        String price = req.getParameter("price");
        if (ObjectUtil.isEmpty(codeNum) || ObjectUtil.isEmpty(userName) || ObjectUtil.isEmpty(price)) {
            throw new ServiceException("银行信息不能为空");
        }
        try {
            Map<String, String> param = new HashMap<String, String>();
            param.put("mch_id",yjjExternalAuthConfig.getMchid());
            //创建订单编号
            param.put("partner_trade_no", "");
            param.put("nonce_str", "");
            //银行卡号
            param.put("enc_bank_no", GetRSAUtil.getRSA(codeNum, WXPayCommon.PRI_KEY));
            //收款方真实姓名
            param.put("enc_true_name", GetRSAUtil.getRSA(userName, WXPayCommon.PRI_KEY));
            //这边要根据微信提供的银行卡名称更换成code码
            param.put("bank_code", "1001");
            //付款金额(即用户申请转账金额)
//            param.put("amount", String.valueOf((int) CommonUtils.mul(Double.parseDouble(price), 100.00)));
            param.put("amount", "1");
            //签名
            String sign = WeixinUtil.createSign(param, yjjExternalAuthConfig.getKey());
            param.put("sign", sign);
            String xml = WeixinUtil.mapToXml(param);
            //发送请求
            String resultXml = HttpClientCustomSSL.httpClientResultPANK(xml);
            Map<String, String> resultMap = WeixinUtil.xmlToMap(resultXml);
            if("SUCCESS".equals(resultMap.get("result_code"))){
                WithdrawalRecordDO withdrawalRecordDO = new WithdrawalRecordDO();
                withdrawalRecordDO.setWxUserId(1L);
                withdrawalRecordDO.setBankName("中国工商银行");
                withdrawalRecordDO.setBankAccount("123456");
                withdrawalRecordMapper.insert(withdrawalRecordDO);
            }
        } catch (Exception e) {
            throw new ServiceException("微信商户转个人银行卡抛出异常");
        }
        return R.ok();
    }

    /**
     * 微信退款回调
     */
    @RequestMapping("/refund/payNotify")
    public void refundPayNotify(HttpServletRequest request) throws Exception {
        wxPayService.refundNotify(request);
    }
}
